/**
 * Description:
 * Class Name:ServerThread
 * Date:2022/5/23 16:50
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_3_基于TCP协议的网络编程._17_3_4_为服务器加入多线程;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class ServerThread implements Runnable{
    Socket socket = null;
    BufferedReader br = null;
    public ServerThread(Socket socket) throws IOException{
        this.socket = socket;
        // 初始化该Socket对应的输入流
        br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    // 定义读取客户端数据的方法
    public String readFromClient(){
        try {
            return br.readLine();
        }
        catch (IOException e){
            // 如果捕获到异常，则表明该Socket对应的客户端已经关闭，删除该Socket
            MyServer.socketList.remove(socket);
        }
        return null;
    }

    @Override
    public void run() {
        try {
            String content = null;
            while ((content = readFromClient()) != null){
                for (var s :
                        MyServer.socketList) {
                    // 遍历socketList中的每个Socket是为了将读到的内容向每个Socket转发一次
                    var ps = new PrintStream(socket.getOutputStream());
                    ps.println("经由服务器回复的："  + content);
                }
            }
        }
        catch (IOException e){
            e.printStackTrace();
        }
    }
}
